const { ADDRGETNETWORKPARAMS, promises } = require("dns");
const { name } = require("ejs");
const express = require("express")
const path = require('path');
const app = express()
const fs = require("fs/promises")
let Users = require("./date/students.json")
app.set("view engine", "ejs")
app.set("views", path.resolve(__dirname, "views"))
app.use(express.static(path.resolve(__dirname, "public")))
app.use(express.urlencoded())
app.get("/", (req, res) => {
})
app.get("/students", (req, res) => { res.render("students", { Users: Users }) })
app.post("/add-students", (req, res) => {
    const id = Users.at(-1) ? Users.at(-1).id + 1 : 1
    const { name, age, gender, address } = req.body
    const newUser = { id: id, name, age: +age, gender, address }
    Users.push(newUser)
    console.log(newUser);
    fs.writeFile(
        path.resolve(__dirname, "./date/students.json")
        , JSON.stringify(Users)).then(() => { res.redirect("/students") }).catch(() => { })
})
app.get("/del_Users", (req, res) => {
    const id = +req.query.id
    Users = Users.filter((User) => User.id !== id)

    fs.writeFile(
        path.resolve(__dirname, "./date/students.json")
        , JSON.stringify(Users)).then(() => { res.redirect("/students") }).catch(() => { })
})
app.get("/res_Users", (req, res) => {
    const id = +req.query.id
    const std = Users.find((User) => User.id === id)
    console.log(std);
    res.render("std_res", { std })
})
app.post(("/res_std"), (req, res) => {
    const { id, name, age, gender, address } = req.body
    const std = Users.find((User) => User.id == id)
    std.name = name
    std.age = +age
    std.gender = gender
    std.address = address
    fs.writeFile(
        path.resolve(__dirname, "./date/students.json")
        , JSON.stringify(Users)).then(() => { res.redirect("/students") }).catch(() => { })
})
app.get("/set_name", (req, res) => {
    name = req.query.name
    res.send("修改成功")
})
app.use((req, res) => {
    res.status(404)
    res.send("<h1>你访问的网站出现问题了........<h1>")
})
app.listen(3000, () => {
    console.log("服务器已启动.....");
})